<template>
    <div class="bookContainer">
        <div class="header">
            <div>
                <el-button type="primary" @click="$router.replace({ name: 'addBook' })"> 新增图书 </el-button>
                <el-button type="danger" :disabled="!selectedCount" style="margin: 0.6rem" @click="multiDelete">
                    批量删除
                </el-button>
                <el-input
                    v-model="searchText"
                    placeholder="请输入标题"
                    :suffix-icon="searchIcon"
                    style="width: 20rem"
                    clearable
                    @input="searchHandler"
                    @clear="refresh"
                />
            </div>
            <span>共有数据：{{ total }} 条</span>
        </div>
        <div class="search" />
        <el-table
            ref="form"
            v-loading="isLoading"
            :data="bookData"
            style="width: 100%"
            empty-text="没有数据"
            element-loading-text="数据加载中..."
            row-key="bookID"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" :reserve-selection="true" />
            <el-table-column prop="bookID" label="图书ID" width="80" />
            <el-table-column prop="coverImg" label="封面" width="140">
                <template #default="scope">
                    <el-image :src="scope.row.coverImg" style="width: 80px; padding: 10px 0" />
                </template>
            </el-table-column>
            <el-table-column prop="title" label="书名" width="160" />
            <el-table-column prop="author" label="作者" width="160" />
            <el-table-column prop="translator" label="译者" width="160" />
            <el-table-column prop="isbn" label="ISBN" width="140" />
            <el-table-column prop="category" label="分类" width="100" />
            <el-table-column prop="price" label="价格" width="100">
                <template #default="scope"> ￥{{ scope.row.price.toFixed(2) }} </template>
            </el-table-column>
            <el-table-column prop="stockNum" label="库存数量" width="100" />
            <el-table-column prop="soldNum" label="售出数量" width="100" />
            <el-table-column prop="pubDate" label="发行时间" width="120" />
            <el-table-column prop="publisher" label="出版社" width="160" />
            <el-table-column prop="language" label="语言" width="100" />
            <el-table-column prop="summary" label="简介" width="300">
                <template #default="scope">
                    <span class="summary">{{ scope.row.summary }} </span>
                </template>
            </el-table-column>
            <el-table-column width="200" label="操作" fixed="right">
                <template #default="scope">
                    <el-button type="primary" @click="updateHandler(scope.row)">修改</el-button>
                    <el-button type="danger" plain @click="deleteHandler(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-drawer
            v-model="drawerOpen"
            size="40rem"
            title="修改图书信息"
            :destroy-on-close="true"
            :before-close="confirmClose"
        >
            <UpdateBook :form="updateForm" @drawer="closeHandler" />
        </el-drawer>
        <div class="footer">
            <el-pagination
                v-model:page-size="pageSize"
                background
                layout="sizes, prev, pager, next"
                :page-count="pageCount"
                :default-page-size="3"
                :page-sizes="[3, 5, 10, 20]"
                :current-page="currentPage"
                @update:current-page="currentPageChange"
            />
            <span>当前选中：{{ selectedCount }} 行</span>
        </div>
    </div>
</template>

<script>
import service from "@/utils/request";
import { Search } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import UpdateBook from "./UpdateBook.vue";
import { markRaw } from "vue";

export default {
    data() {
        return {
            bookData: [],
            pageCount: 0,
            pageSize: 3,
            currentPage: 1,
            searchText: "",
            selectedRows: [],
            selectedCount: 0,
            selectedId: [],
            isLoading: true,
            total: 0,
            drawerOpen: false,
            searchIcon: markRaw(Search),
        };
    },
    components: {
        Search,
        UpdateBook,
    },
    watch: {
        pageSize(oldVal) {
            this.pageSize = oldVal;
            // console.log(this.pageSize);
            this.refresh();
        },
    },
    beforeMount() {
        this.refresh();
    },
    methods: {
        // 页面刷新
        async refresh() {
            this.searchTitle = "";
            this.isLoading = true;
            await service
                .get(`/book/list/${this.currentPage}/${this.pageSize}`)
                .then((res) => {
                    this.total = res.data.data.total;
                    this.bookData = res.data.data.records;
                    this.pageCount = res.data.data.pages;
                })
                .catch((err) => {
                    ElMessage({
                        type: "error",
                        message: "数据请求出错：" + err,
                    });
                });
            this.isLoading = false;
        },
        // 搜索
        async searchHandler() {
            if (this.searchText !== "") {
                this.isLoading = true;
                await service
                    .get(`/book/list/${this.currentPage}/${this.pageSize}?title=${this.searchText}`)
                    .then((res) => {
                        // console.log(res.data.data);
                        this.bookData = res.data.data.records;
                        this.total = res.data.data.total;
                        this.pageCount = res.data.data.pages;
                        // console.log(this.bookData);
                    });
                this.isLoading = false;
            } else {
                this.refresh();
            }
        },
        // 多选操作
        handleSelectionChange(rows) {
            // console.log(rows);
            this.selectedRows = rows;
            this.selectedCount = this.selectedRows.length;
            this.selectedId = [];
            if (rows) {
                rows.forEach((row) => {
                    if (row) {
                        this.selectedId.push(row.bookID);
                    }
                });
            }
            // console.log(this.selectedId);
        },
        closeHandler() {
            this.drawerOpen = false;
            this.searchHandler();
        },
        // 批量删除
        multiDelete() {
            this.selectedId.forEach((item) => {
                service.delete(`/book/deleteById/${item}`).then(() => {});
            });
            ElMessage({
                type: "success",
                message: "删除成功",
            });
            this.refresh();
        },
        // 更新
        updateHandler(e) {
            this.updateForm = e;
            this.drawerOpen = true;
        },
        // 页码切换
        currentPageChange(e) {
            this.currentPage = e;
            // console.log(this.currentPage);
            this.refresh();
        },
        // 删除
        deleteHandler(e) {
            // console.log(e.bookID);
            ElMessageBox.confirm("确认要删除吗？", "提示", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    service
                        .delete(`/book/deleteById/${e.bookID}`)
                        .then(() => {
                            ElNotification({
                                title: "Success",
                                type: "success",
                                message: "删除成功",
                            });
                            this.refresh();
                        })
                        .catch((err) => {
                            ElNotification({
                                title: "Error",
                                message: "删除失败：" + err,
                                type: "error",
                            });
                        });
                })
                .catch(() => {
                    ElMessage({
                        type: "info",
                        message: "取消删除",
                    });
                });
        },
        confirmClose() {
            ElMessageBox.confirm("您有未保存的信息，确认要关闭吗？", "提示", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.drawerOpen = false;
                })
                .catch();
        },
    },
};
</script>

<style lang="scss" scoped>
.bookContainer {
    display: flex;
    flex-direction: column;

    .header {
        display: flex;
        flex-direction: row;
        // margin-bottom: 1rem;
        justify-content: space-between;
        align-items: center;
    }

    .footer {
        margin-top: 1rem;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
    }

    .summary {
        display: -webkit-box;
        overflow: hidden;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 4;
    }
}
</style>
